﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Mvc.StarterSite.Controllers;
using System.Web.Mvc;
using MvcEngine.Mvc.Models.ViewModels;
using MvcEngine.Blog.Models.Entities;
using MvcEngine.Blog.Repositories;
using MvcEngine.Core;
using MvcEngine.Blog.Filters;
using MvcEngine.Mvc.Filters;
using MvcEngine.Mvc;
using MvcEngine.Blog.Components.Extensions;
using MvcEngine.Mvc.Controllers;
using MvcEngine.Core.Pagination;
using MvcEngine.Blog.Managers;
using MvcEngine.Core.Content;
using MvcEngine.Core.Helpers;
using MvcEngine.Blog.Models;
using MvcEngine.Mvc.Extensions;

namespace MvcEngine.Blog.BackOffice.Controllers
{
    public class BlogRecentPostsController : SubController
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public MvcEngineModel Settings(int ctrId)
        {
            var blogRecentPosts = ContentManager.Current.GetPageContent(ctrId);
            Guard.ThrowIfNull(blogRecentPosts, string.Format("Page content {0} does not exist.", ctrId));
            RecentPostsPageContent content = new RecentPostsPageContent(blogRecentPosts);

            return new BlogRecentPostsSettingsViewModel()
            {
                PostCount = content.PostCount
            };
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AntiForgeryValidationFilter]
        public object Settings(int ctrId, int postCount)
        {
            if (ModelState.IsValid)
            {
                var blogRecentPosts = ContentManager.Current.GetPageContent(ctrId);
                Guard.ThrowIfNull(blogRecentPosts, string.Format("Page content {0} does not exist.", ctrId));

                RecentPostsPageContent content = new RecentPostsPageContent(blogRecentPosts);
                content.PostCount = postCount;

                blogRecentPosts.Fields = content.Fields;
                ContentManager.Current.SavePageContent(blogRecentPosts);

                return Json(new { model = "valid" });
            }
            return Json(new { model = "invalid", errors = ModelState.GetErrors() });
        }
    }
}
